package com.mr.apigateway.filter;

import com.mr.apigateway.constant.Constant;
import com.mr.apigateway.utils.CookieUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_DECORATION_FILTER_ORDER;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * Class: AuthFilter
 * User (作者):MRui
 * TODO (描述)：权限拦截器
 * Date 2018-11-15 22:19
 */
@Component
public class AuthFilter extends ZuulFilter {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**返回过滤器的类型。有pre、route、post、error等几种取值，分别对应上文的几种过滤器。详细可以参考com.netflix.zuul.ZuulFilter.filterType() 中的注释。*/
    @Override
    public String filterType() {
        //前置过滤器（请求前） 可用来限流 鉴权 参数校验，请求转发等
        //POST_TYPE（请求后） 后置过滤器 可用记录统计，日志等
        return PRE_TYPE;
    }
    /**，返回一个int值来指定过滤器的执行顺序，不同的过滤器允许返回相同的数字*/
    @Override
    public int filterOrder() {
        return PRE_DECORATION_FILTER_ORDER - 1;
    }
    /**是否执行*/
    @Override
    public boolean shouldFilter() {
        return false;
    }
    /** 逻辑*/
    @Override
    public Object run() throws ZuulException {
        /**  （逻辑分为AuthBuyerFilter,AuthSellerFilter两个文件来执行）
         * /order/create  只能买家访问
         * /order/finish  只能卖家访问
         * /product/list  都可以访问
         */
        //获取上下文
        RequestContext requestContext = RequestContext.getCurrentContext();
        //获取request
        HttpServletRequest request = requestContext.getRequest();
        //当地址是买家的时候
        if ("/order/order/create".equals(request.getRequestURI())){
            Cookie cookie = CookieUtil.get(request, "openid");
            if (cookie == null || StringUtils.isEmpty(cookie.getValue())){
                //不通过
                requestContext.setSendZuulResponse(false);
                //设置http状态码 401权限不足
                requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
            }
        }
        if ("/order/order/finish".equals(request.getRequestURI())){
            Cookie cookie = CookieUtil.get(request, "token");
            if (cookie == null
                    || StringUtils.isEmpty(cookie.getValue())
                    || StringUtils.isEmpty(redisTemplate.opsForValue().get(String.format(Constant.REDIS_TOKEN_PREFIX, cookie.getValue())))){
                //不通过
                requestContext.setSendZuulResponse(false);
                //设置http状态码 401权限不足
                requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
            }
        }

        return null;
    }
}
